/**
 * AI 作画
 * 
 */

import { Service } from "egg";
import axios from "axios";

const BaiduAIToken = 'BaiduAccessToken'

const TokenAccessHost = 'https://aip.baidubce.com/oauth/2.0/token'


type AiParam = {
  draw: string
  query: string
}

// 基础版
const baseDraw: AiParam = {
  draw: 'https://aip.baidubce.com/rpc/2.0/ernievilg/v1/txt2img',
  query: 'https://aip.baidubce.com/rpc/2.0/ernievilg/v1/getImg'
}

type basicParam = {
  text: string
  resolution: string
  style: string
  num?: number
}



export default class BaiduAIService extends Service {

  /**
   * 百度获取accessToken
   */
  async getToken() {

    // const token = this.service.cache.get(BaiduAIToken)
    // if (token) {
    //   return token
    // }
    const { Key, Secret } = this.config.baiduAI
    const { data } = await axios.post(`${TokenAccessHost}?client_id=${Key}&client_secret=${Secret}&grant_type=client_credentials`, {
      'headers': {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      }
    })
    // this.service.cache.set(BaiduAIToken, data.access_token, data.expires_in)

    return data.access_token
  }

  async drawImgBasic(option: basicParam) {

    const op = { ...option }
    const token = await this.getToken()
    op.num = option.num || 1
    const { data } = await axios.post(`${baseDraw.draw}?access_token=${token}`, op, {
      headers: {
        'Content-Type': 'application/json'
      }
    })

    return data
  }

  async queryTaskBisic(taskId: string) {
    const result = await this.service.cache.get(taskId)

    // 如果生成过了 直接返回
    if (result) {
      return result
    }
    const token = await this.getToken()

    const { data } = await axios.post(`${baseDraw.query}?access_token=${token}`, {
      taskId
    })

    if (data?.status === 1) {
      this.service.cache.set(taskId, data, 60 * 60 * 24)
    }
    return data
  }

  createChuangKetSign() {
    const uid = this.ctx.state.user.shop_id
    const option: Record<string, any> = {
      app_id: this.config.chuangkit.AppId,
      expire_time: Date.now() + 1000 * 60 * 4,
      user_flag: uid,
      device_type: 1,
      // hide_logo: 1,
      kind_id: 447,
      charge_type: 0,
      charging_template_limit: 0,
      coop_font_limit: 0,
      coop_material_limit: 0
    }

    const value = {
      ...option,
      // app_secret: 

    }

    const sign = this.ctx.helper.md5(Object.keys(value).sort()
      .map(key => `${key}=${value[key]}`)
      .join('&') + this.config.chuangkit.Secret).toUpperCase()

    return {
      ...option,
      sign
    }
  }
} 